package com.skyvin.nreceipts.receipts.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.skyvin.nreceipts.common.controller.BaseController;
import com.skyvin.nreceipts.common.document.Receipt;
import com.skyvin.nreceipts.common.document.ReceiptCategory;
import com.skyvin.nreceipts.common.document.ReceiptItem;
import com.skyvin.nreceipts.common.document.ReceiptItemCategory;
import com.skyvin.nreceipts.common.document.Retailer;
import com.skyvin.nreceipts.common.dto.ReceiptItemGridDTO;
import com.skyvin.nreceipts.common.value.JQGridResponse;
import com.skyvin.nreceipts.common.value.MessageValue;
import com.skyvin.nreceipts.receipts.mongorepository.ReceiptItemRepository;
import com.skyvin.nreceipts.receipts.mongorepository.ReceiptRepository;
import com.skyvin.nreceipts.receipts.service.ReceiptService;
import com.skyvin.nreceipts.user.service.UserService;

@Controller
@RequestMapping("rec")
public class ReceiptController extends BaseController {

	private Logger logger = Logger.getLogger(ReceiptController.class);
	
	@Autowired 
	UserService userService;
	
	@Autowired 
	ReceiptService receiptsService;
	
	@Autowired
	ReceiptRepository receiptRepository;
	
	@Autowired 
	MongoTemplate mongoTemplate; 
	
	@Autowired
	ReceiptItemRepository receiptItemRepository;
	
	@RequestMapping(value = "/loadReceiptsCreatePage", method = RequestMethod.GET)
	public String loadReceiptsCreatePage(Model model) {
		Receipt receipt = new Receipt();
		model.addAttribute("receipt", receipt);
		return "receipts/receiptsedit";
	}
	
	@RequestMapping(value = "/loadReceiptsEditPage/{receiptID}", method = RequestMethod.GET)
	public String loadEditReceiptsPageForReceiptId(@PathVariable(value="receiptID") String receiptID, Model model) {
		Receipt receipt = receiptsService.getMyReceipt(receiptID);
		model.addAttribute("receipt", receipt);
		return "receipts/receiptsedit";
	}
	
	@RequestMapping(value = "loadReceiptsViewPage", method = RequestMethod.GET)
	public String loadViewReceiptsPage(Model model) {
		return "receipts/receiptsview";
	}

	@RequestMapping(value="/viewReceiptItemDetails", method=RequestMethod.GET)
	@ResponseBody
	public JQGridResponse viewReceiptItemDetails(@RequestParam("receiptId") String receiptId, @RequestParam("_search") Boolean search,
    		@RequestParam(value="filters", required=false) String filters,
    		@RequestParam(value="page", required=false) Integer page,
    		@RequestParam(value="rows", required=false) Integer rows,
    		@RequestParam(value="sidx", required=false) String sidx,
    		@RequestParam(value="sord", required=false) String sord) {
		
		List<ReceiptItem> receiptItemList = null;
		List<ReceiptItemGridDTO> receiptItemGridDTOList = null;
		JQGridResponse jqGridResponse = new JQGridResponse();
		if(receiptId==null || receiptId.equals("")) {
			logger.info("Inside create mode, returning empty list..");
		} else {
			receiptItemList = receiptsService.getMyReceiptItems(receiptId); 
			receiptItemGridDTOList = convertReceiptItemToGridDTO(receiptItemList, receiptId);
		}
		jqGridResponse.setRows(receiptItemGridDTOList);
		return jqGridResponse;
	}

	@RequestMapping(value = "/saveReceipt", method = RequestMethod.POST)
	public @ResponseBody MessageValue saveReceipt(Receipt receipt) {
		receipt.setUserPID(getCurrentUserPID());
		ReceiptCategory receiptCategory = receipt.getReceiptCategory();
		Retailer retailer = receipt.getRetailer();
		
		if(receiptCategory.getId() != null && receiptCategory.getId().equals("")) {
			receiptCategory.setId(null);
		}
		if(retailer.getId()!= null && retailer.getId().equals("")) {
			retailer.setId(null);
		}
		if(receipt.getId() != null && receipt.getId().equals("")) {
			receipt.setId(null);
		}
		Receipt receiptCreated = receiptsService.saveReceiptHeader(receipt);
		
		MessageValue messageValue = new MessageValue("Receipt information has been updated !!");
		messageValue.setObject(receiptCreated);
		return messageValue;
	}
	
	@RequestMapping(value = "/saveReceiptItem", method = RequestMethod.POST)
	public @ResponseBody MessageValue saveReceiptItem(ReceiptItemGridDTO receiptItemGridDTO,@RequestParam("oper") String operation) {
		MessageValue message = new MessageValue();
		
		ReceiptItem receiptItem = convertGridItemToReceiptItem(receiptItemGridDTO);
		receiptItem.setUserPID(getCurrentUserPID());
		receiptsService.saveReceiptItem(receiptItem);
		logger.info("Operation : " + operation);
		if(operation.equals("add")) {
			//receiptsService.saveReceiptItem(receiptItem);
		} else if(operation.equals("edit")) {
			
		}
		
		

		message.setMessage("Receipt item " + receiptItem.getName()+ " added successfully !!");
		//message.setDetailedMessage("http://farm4.staticflickr.com/3510/3208351775_e06db18ee4.jpg");

		return message;
	}

	@RequestMapping(value="/viewReceiptDetails", method=RequestMethod.GET)
	@ResponseBody
	public JQGridResponse viewReceiptDetails(@RequestParam("_search") Boolean search,
    		@RequestParam(value="filters", required=false) String filters,
    		@RequestParam(value="page", required=false) Integer page,
    		@RequestParam(value="rows", required=false) Integer rows,
    		@RequestParam(value="sidx", required=false) String sidx,
    		@RequestParam(value="sord", required=false) String sord) {
		
		List<Receipt> receiptList = null;
		
		JQGridResponse jqGridResponse = new JQGridResponse();
		Pageable pageRequest = new PageRequest(page-1, rows);
		long count = 0;
		int countOfReceiptListReturned = 0;
		
		//receiptItemPageList = receiptItemRepository.findAll(pageRequest);
		Query query = new Query();
		query.addCriteria(Criteria.where("userPID").is(getCurrentUserPID()));
		query.skip((page-1) * rows);
		query.limit(rows);
		
		Query countQuery = new Query();
		countQuery.addCriteria(Criteria.where("userPID").is(getCurrentUserPID()));
		
		receiptList = mongoTemplate.find(query, Receipt.class, receiptsService.getMyCollection(Receipt.class));
		if(receiptList!= null) {
			countOfReceiptListReturned = receiptList.size();
		}
		
		count = mongoTemplate.count(new Query(), receiptsService.getMyCollection(Receipt.class));
		logger.info("Count : " + count);
		logger.info("Records retrieved : " + countOfReceiptListReturned);
		//receiptItemList = receiptItemPageList.getContent();
		//receiptItemDTOList = ReceiptItemMapper.map(receiptItemPageList);
		//receiptItemGridDTOList = convertReceiptItemToGridDTO(receiptList);
		
		
		
		jqGridResponse.setPage(1);
		
		if(receiptList!= null) {
			
			jqGridResponse.setRecords(countOfReceiptListReturned);
			jqGridResponse.setTotal((int) count);
			jqGridResponse.setPage(page);
		}
		jqGridResponse.setRows(receiptList);
		return jqGridResponse;
	}

	


	@RequestMapping(value="/deleteReceiptItem", method=RequestMethod.POST)
	public @ResponseBody MessageValue deleteReceiptItem(@RequestParam("oper") String oper, @RequestParam("id") String receiptItemPID) {
		MessageValue message = new MessageValue();
		receiptsService.deleteMyReceiptItem(receiptItemPID);
		message.setMessage("Receipt item deleted !!");
		return message;
	}
	
	@RequestMapping(value="/deleteReceipt", method=RequestMethod.POST)
	public @ResponseBody MessageValue deleteReceipt(@RequestParam("oper") String oper, @RequestParam("id") String receiptPID) {
		MessageValue message = new MessageValue();
		logger.info("Receipt deleted..");
		receiptsService.deleteMyReceipt(receiptPID);
		message.setMessage("Receipt deleted !!");
		return message;
	}
	
	private ReceiptItem convertGridItemToReceiptItem(
			ReceiptItemGridDTO receiptItemGridDTO) {
		ReceiptItem receiptItem = new ReceiptItem();
		ReceiptItemCategory receiptItemCategory = new ReceiptItemCategory();
		Receipt receipt = new Receipt();
		receiptItem.setId(receiptItemGridDTO.getId());
		receiptItem.setItemId(receiptItemGridDTO.getItemId());
		receiptItem.setName(receiptItemGridDTO.getReceiptItemName());
		receiptItem.setPrice(receiptItemGridDTO.getPrice());
		
		receiptItemCategory.setValue(receiptItemGridDTO.getReceiptItemCategory().getValue());
		receiptItem.setReceiptItemCategory(receiptItemCategory);
		receipt.setId(receiptItemGridDTO.getReceiptIdHidden());
		receiptItem.setReceipt(receipt);
		
		return receiptItem;
	}
	
	
	private List<ReceiptItemGridDTO> convertReceiptItemToGridDTO(
			List<ReceiptItem> receiptItemList, String receiptID) {
		List<ReceiptItemGridDTO> receiptItemGridDTOList = new ArrayList<ReceiptItemGridDTO>();
		for (ReceiptItem receiptItem : receiptItemList) {
			ReceiptItemGridDTO receiptItemGridDTO = new ReceiptItemGridDTO();
			receiptItemGridDTO.setId(receiptItem.getId());
			receiptItemGridDTO.setReceiptIdHidden(receiptID);
			receiptItemGridDTO.setItemId(receiptItem.getItemId());
			receiptItemGridDTO.setReceiptItemName(receiptItem.getName());
			receiptItemGridDTO.setPrice(receiptItem.getPrice());
			receiptItemGridDTOList.add(receiptItemGridDTO);
			
			ReceiptItemCategory receiptItemCategory = receiptItem.getReceiptItemCategory();
			receiptItemGridDTO.setReceiptItemCategory(receiptItemCategory);
		}
		return receiptItemGridDTOList;
	}
}